package com.example.study1206.service;

import com.example.study1206.service.MultipleService;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.DescribeTopicsResult;
import org.apache.kafka.clients.admin.ListTopicsResult;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.ExecutionException;

@Component("Kafka")
public class KafkaServiceImp implements MultipleService {
    @Autowired
    AdminClient adminClient;

    /*目前kafka实现的方法都是针对topic，对于consumer还未加入*/
    @Override
    public String getByKey(String key) {
        DescribeTopicsResult result = adminClient.describeTopics(
                Arrays.asList(key));
        String shownResult = null;
        try {
            shownResult = result.all().get().values().toString();
        } catch (ExecutionException e) {
            return "该topic不存在";
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return shownResult;
    }

    @Override
    public String set(String key, String value) {
        adminClient.createTopics(Arrays.asList(new NewTopic(key, Integer.parseInt(value), (short) 1)));
        return "Set a new Topic";
    }

    @Override
    public Boolean isExist(String key) {
        return getByKey(key) != "该topic不存在";
    }

    @Override
    public Long delete(String key) {

        adminClient.deleteTopics(Arrays.asList(key));
        return 1L;
    }

    @Override
    public String getAll() {
        ListTopicsResult result = adminClient.listTopics();
        try {
            return result.names().get().toString();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
